package com.wyl.template.config.shiro.filter;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @Auther: wyl
 * @Date: 2021/4/29
 * @Description:
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    /**
     * 解决切换用户时，如果没有注销之前的用户，切换失败的问题
     *
     * @param request     请求
     * @param response    响应
     * @param mappedValue 映射值
     * @return 是否允许登录
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response,
                                      Object mappedValue) {
        Subject subject = getSubject(request, response);
        boolean isAuthenticated = subject.isAuthenticated();
        if (isLoginRequest(request, response) && isAuthenticated) {
            subject.logout();
            return false;
        }
        return isAuthenticated;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        // 继续调用 @PostMapping("/login")
        return true;
    }
}
